package org.flink.marketing.util;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


/**
 *
 */
public class HttpClientUtil {

	/**
	 * head请求
	 *
	 * @param url
	 * @param header
	 * @param resultHeaderKey
	 * @return
	 */
	public static Header[] head(String url, Map<String, String> header, String resultHeaderKey) {
//		HttpClient client = new DefaultHttpClient();
		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpHead httpHead = new HttpHead(url);
		Header[] headers = null;
		for (String key : header.keySet()) {
			httpHead.addHeader(key, header.get(key));
		}
		try {
			HttpResponse httpResponse = client.execute(httpHead);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
				headers = httpResponse.getHeaders(resultHeaderKey);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return headers;
	}

	/**
	 * post请求
	 *
	 * @param url
	 * @param json
	 * @return
	 */
	public static JSONObject post(String url, JSONObject json) {
//		HttpClient client = new DefaultHttpClient();
		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		JSONObject result = null;
		try {
			StringEntity s = new StringEntity(json.toString(), "UTF-8");
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");
			post.setEntity(s);
			HttpResponse httpResponse = client.execute(post);
			HttpEntity entity = httpResponse.getEntity();
			String charset = EntityUtils.getContentCharSet(entity);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = JSONObject.parseObject(EntityUtils.toString(entity, charset));
			} else {
				throw new Exception(EntityUtils.toString(entity, charset));
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * put请求
	 *
	 * @param url
	 */
	public static void put(String url) {
		HttpClient client = new DefaultHttpClient();
		HttpPut put = new HttpPut(url);
		try {
			HttpResponse httpResponse = client.execute(put);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * post请求数据，读取接口响应
	 * @param url
	 * @param data
     * @return
     */
	public static String postStr(String url, String data) throws IOException {
		Log log = LogFactory.getLog(HttpClientUtil.class);
		log.info("send post: "+data);
//		HttpClient client = new DefaultHttpClient();
		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		StringEntity s = new StringEntity(data, "UTF-8");
		s.setContentEncoding("UTF-8");
		s.setContentType("application/json");
		post.setEntity(s);
		HttpResponse httpResponse = client.execute(post);
		HttpEntity entity = httpResponse.getEntity();
		String charset = EntityUtils.getContentCharSet(entity);
		String result = EntityUtils.toString(entity, charset);
		log.info("send result: "+result);
		return result;
	}

	public static String sendHttpRequest(String url, String signedBody) {
        Log log = LogFactory.getLog(HttpClientUtil.class);
        HttpURLConnection conn = null;
        BufferedReader reader = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			// 加入数据
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);

			BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
			buffOutStr.write(signedBody.getBytes());
			buffOutStr.flush();
			buffOutStr.close();

			// 获取输入流
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			//log.info(e);
		} finally {
		    if (conn != null){
		        conn.disconnect();
            }
		    if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		return null;
	}


	public static String doGet(String url) {
		return doGet(url, new HashMap<String, Object>());
	}

	/**
	 * 发送 GET 请求（HTTP），K-V形式
	 *
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doGet(String url, Map<String, Object> params) {
		Log log = LogFactory.getLog(HttpClientUtil.class);
		String apiUrl = url;
		StringBuffer param = new StringBuffer();
		int i = 0;
		for (String key : params.keySet()) {
			if (i == 0) {
				param.append("?");
			} else {
				param.append("&");
				param.append(key).append("=").append(params.get(key));
				i++;
			}
		}
		apiUrl += param;
		String result = null;
//		HttpClient httpclient = new DefaultHttpClient();
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		try {
			HttpGet httpPost = new HttpGet(apiUrl);
			HttpResponse response = httpclient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();

			System.out.println("执行状态码 : " + statusCode);

			HttpEntity entity = response.getEntity();
			if (entity != null) {
//				InputStream instream = entity.getContent();
//				result = IOUtils.toString(instream, "UTF-8");
				result = EntityUtils.toString(entity);
			}
		} catch (IOException e) {
			log.error("IOException:",e);
		}
		return result;
	}
}
